﻿using System.Linq;
using TSU.FAMC.ComputerEngineering.Classes.Enums;

namespace TSU.FAMC.ComputerEngineering.Classes.OrandTrees.Basis
{
    /// <summary>
    /// Vertex of ORAND-tree.
    /// </summary>
    public class Vertex : TreeElement
    {
        // Properties

        /// <summary>
        /// Vertex type.
        /// </summary>
        public VertexType Type = VertexType.Input;

        /// <summary>
        /// Inverse flag.
        /// </summary>
        public bool IsInverted;


        // Methods

        /// <summary>
        /// Default constructor.
        /// </summary>
        public Vertex()
        {
            Type = VertexType.Undefined;
        }

        /// <summary>
        /// Links child vertex via edge.
        /// </summary>
        /// <param name="vertex">Vertex to link.</param>
        public Edge LinkChildVertex(Vertex vertex)
        {
            var edge = new Edge();
            LinkChild(edge);
            edge.LinkChild(vertex);

            return edge;
        }

        /// <summary>
        /// Unlinks parent or child vertex with it's edge.
        /// </summary>
        /// <param name="vertex">Vertex to unlink.</param>
        public void UnlinkVertex(Vertex vertex)
        {
            // examining children
            foreach (var edge in new ElementInterface(Children).Where(edge => edge.Children.Contains(vertex)))
            {
                edge.UnlinkElement(vertex);
                UnlinkElement(edge);
            }

            // examining parents
            foreach (var edge in new ElementInterface(Parents).Where(edge => edge.Parents.Contains(vertex)))
            {
                edge.UnlinkElement(vertex);
                UnlinkElement(edge);
            }
        }

        /// <summary>
        /// Clones vertex.
        /// </summary>
        /// <returns>Clones the vertex.</returns>
        public override object Clone()
        {
            var clone = new Vertex
                            {
                                Data = Data,
                                Parents = new ElementInterface(Parents),
                                Children = new ElementInterface(Children),
                                Type = Type,
                                IsInverted = IsInverted
                            };

            return clone;
        }
    }
}
